package com.smart.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.smart.common.utils.AssertUtil;
import com.smart.context.SessionContext;
import com.smart.mapper.JiansheProjectMapper;
import com.smart.mapper.ProjectMapper;
import com.smart.mapper.QrCodeMapper;
import com.smart.model.convert.ProjectConvert;
import com.smart.model.domain.ProjectDO;
import com.smart.model.domain.QrCodeDO;
import com.smart.model.dtomapper.ManageTempUserRegistrationDtoMapper;
import com.smart.model.domain.ManageTempUserRegistrationDO;
import com.smart.mapper.ManageTempUserRegistrationMapper;
import com.smart.model.request.ManageTempUserRegistrationRequest;
import com.smart.model.request.ProjectRequest;
import com.smart.model.vo.*;
import com.smart.service.DictItemService;
import com.smart.service.ManageTempUserRegistrationService;
import com.smart.model.convert.ManageTempUserRegistrationConvert;
import com.smart.service.StreetService;
import com.smart.utils.DateUtils;
import com.smart.utils.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.*;

import static com.smart.utils.PageUtils.getOrderBy;

/**
 * @author zyh
 */
@Service
public class ManageTempUserRegistrationServiceImpl extends ServiceImpl<ManageTempUserRegistrationMapper, ManageTempUserRegistrationDO> implements ManageTempUserRegistrationService {
    @Autowired
    private ManageTempUserRegistrationMapper manageTempUserRegistrationMapper;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private StreetService streetService;
    @Autowired
    private DictItemService itemService;
    @Autowired
    private JiansheProjectMapper jiansheProjectMapper;
    @Autowired
    private QrCodeMapper codeMapper;

    /**
     * 云监管平台临时人员进出查询前工程查询校验
     * @param request
     * @return
     */
    @Override
    public List<HashMap<String,Object>> superviseVerify(ProjectRequest request) {
        Long jiansheUnitId = SessionContext.getJiansheUnitId();
        if (!ObjectUtils.isEmpty(jiansheUnitId)&&!request.getSuperviseOrManage()){//云管理端查询
            List<Long> projectIds = jiansheProjectMapper.selectAllProjectId(jiansheUnitId);
            request.setProjectIds(projectIds);
        }
        List<HashMap<String,Object>> projectDO = projectMapper.selectByProjectNumber(request);
        return projectDO;
    }

    @Override
    public Object superviseAddress() {
        List<ProjectDO> projectDOList = projectMapper.selectDOList(null);
        List<StreetVO> streetVOS = streetService.queryStreetByAreaCode("110115");
        List<DictItemVO> projectType = itemService.queryDictItemByDictCode("PROJECT_TYPE");
        List<ProjectVO> projectVOList = ProjectConvert.buildProjectVoList(projectDOList);
        Map<String, Object> addressMap = new HashMap<>();
        streetVOS.forEach(streetVO -> {
            List<HashMap<String,Object>> projectTwo = new ArrayList<>();
            projectVOList.forEach(projectVO -> {
                addressMap.put(streetVO.getName(), new ArrayList<>());
                if (streetVO.getCode().equals(projectVO.getStreetCode())) {
                    HashMap<String, Object> hashMap = new HashMap<>();
                    hashMap.put("projectId",projectVO.getId());
                    hashMap.put("projectName",projectVO.getProjectName());
                    projectTwo.add(hashMap);
                }
            });
            addressMap.put(streetVO.getName(), projectTwo);
        });
        Map<String, Object> projectTypeMap = new HashMap<>();
        projectType.forEach(itemVO -> {
            List<HashMap<String,Object>> projectOne = new ArrayList<>();
            projectVOList.forEach(projectVO -> {
                projectTypeMap.put(itemVO.getDictItemName(), new ArrayList<>());
                if (itemVO.getDictItemCode().equals(projectVO.getEngineeringType())) {
                    HashMap<String, Object> hashMap = new HashMap<>();
                    hashMap.put("projectId",projectVO.getId());
                    hashMap.put("projectName",projectVO.getProjectName());
                    projectOne.add(hashMap);
                }
            });
            projectTypeMap.put(itemVO.getDictItemName(),projectOne);
        });
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("type",projectTypeMap);
        hashMap.put("address",addressMap);
        return hashMap;
    }

    /**
     * 云监管、云服务、云管理平台临时人员进出场记录查询-根据项目查询
     * @param request
     * @param pageable
     * @return
     */
    @Override
    public PageInfo<List<ManageTempUserRegistrationVO>> supervisePageQueryTempRecordsByProject(ManageTempUserRegistrationRequest request, Pageable pageable) {
        PageHelper.startPage(request.getPageNum(),request.getPageSize(),getOrderBy(pageable.getSort())).setReasonable(true);
        List<ManageTempUserRegistrationDO> userRegistrationDOList = manageTempUserRegistrationMapper.selectByProject(request);
        PageInfo pageInfo = new PageInfo(userRegistrationDOList);
        List<ManageTempUserRegistrationVO> manageTempUserRegistrationVOS = ManageTempUserRegistrationConvert.buildManageTempUserRegistrationVoList(userRegistrationDOList);
        if (ObjectUtils.isEmpty(manageTempUserRegistrationVOS)){
            return new PageInfo<>(new ArrayList<>());
        }
        fillInfo(manageTempUserRegistrationVOS);
        pageInfo.setList(manageTempUserRegistrationVOS);
        return pageInfo;
    }

    /**
     * 云监管、云管理平台临时人员进出场记录查询-根据人员信息查询
     * @param request
     * @param pageable
     * @return
     */
    @Override
    public PageInfo<List<ManageTempUserRegistrationVO>> supervisePageQueryTempRecordsByPerson(ManageTempUserRegistrationRequest request, Pageable pageable) {
        Long jiansheUnitId = SessionContext.getJiansheUnitId();
        if (!ObjectUtils.isEmpty(jiansheUnitId)){
            List<Long> projectIds = jiansheProjectMapper.selectAllProjectId(jiansheUnitId);
            request.setProjectIds(projectIds);
        }
        PageHelper.startPage(request.getPageNum(),request.getPageSize(),getOrderBy(pageable.getSort())).setReasonable(true);
        List<ManageTempUserRegistrationDO> userRegistrationDOList = manageTempUserRegistrationMapper.selectByPhoneOrName(request);
        PageInfo pageInfo = new PageInfo(userRegistrationDOList);
        List<ManageTempUserRegistrationVO> manageTempUserRegistrationVOS = ManageTempUserRegistrationConvert.buildManageTempUserRegistrationVoList(userRegistrationDOList);
        if (ObjectUtils.isEmpty(manageTempUserRegistrationVOS)){
            pageInfo.setList(new ArrayList());
            return pageInfo;
        }
        fillInfo(manageTempUserRegistrationVOS);
        pageInfo.setList(manageTempUserRegistrationVOS);
        return pageInfo;
    }

    private void fillInfo(List<ManageTempUserRegistrationVO> manageTempUserRegistrationVOS) {
        List<DictItemVO> type = itemService.queryDictItemByDictCode("PROJECT_TYPE");//工程类型
        List<StreetVO> streetVOS = streetService.queryStreetByAreaCode("110115");//地点
        for (ManageTempUserRegistrationVO vo : manageTempUserRegistrationVOS) {
            //详细地址
            String province = vo.getProvince();
            String city = vo.getCity();
            String area = vo.getArea();
            String resideAddress = vo.getAddressDetails();
            if (org.apache.commons.lang3.StringUtils.isEmpty(province)){
                province = "";
            }
            if (org.apache.commons.lang3.StringUtils.isEmpty(city)){
                city = "";
            }
            if (org.apache.commons.lang3.StringUtils.isEmpty(area)){
                area = "";
            }
            if (org.apache.commons.lang3.StringUtils.isEmpty(resideAddress)){
                resideAddress = "";
            }
            String address = province+city+area+resideAddress;
            vo.setAddressDetails(address);
            //项目信息
            ProjectDO project = projectMapper.selectDOById(vo.getProjectId());
            //出入口信息
            QrCodeDO e = codeMapper.selectDOById(vo.getEntranceAddress());//入口
            QrCodeDO p = codeMapper.selectDOById(vo.getApproachAddress());//出口
            if (!ObjectUtils.isEmpty(e)){
                vo.setEntranceAddressName(e.getAddress());
            }
            if (!ObjectUtils.isEmpty(p)){
                vo.setApproachAddressName(p.getAddress());
            }
            if (project != null) {
                vo.setProjectName(project.getProjectName());
                vo.setProjectNumber(project.getProjectNumber());
                vo.setQualityRegistrationNumber(project.getQualityRegistrationNumber());
                vo.setEngineeringType(type.stream().filter(itemVO -> itemVO.getDictItemCode().equals(project.getEngineeringType())).findFirst().orElse(new DictItemVO()).getDictItemName());
                vo.setStreet(streetVOS.stream().filter(streetVO -> streetVO.getCode().equals(project.getStreetCode())).findFirst().orElse(new StreetVO()).getName());
                vo.setShigongUnit(project.getShigongUnit());
            }
        }
    }

    @Override
    public ManageTempUserRegistrationVO getByKey(long id) {
        ManageTempUserRegistrationDO manageTempUserRegistrationDO = getById(id);
        ManageTempUserRegistrationVO manageTempUserRegistrationVO = ManageTempUserRegistrationDtoMapper.INSTANCE.do2VO(manageTempUserRegistrationDO);
        return manageTempUserRegistrationVO;
    }

    @Override
    public List<ManageTempUserRegistrationVO> listQuery(ManageTempUserRegistrationRequest request) {
        List<ManageTempUserRegistrationDO> list = list();
        List<ManageTempUserRegistrationVO> manageTempUserRegistrationVOS = ManageTempUserRegistrationConvert.buildManageTempUserRegistrationVoList(list);
        return manageTempUserRegistrationVOS;
    }

    /**
     * 入场和离场登记
     * @param request
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object add(ManageTempUserRegistrationRequest request) {
        String userName = request.getUserName();
        String userPhone = request.getUserPhone();
        Long projectId = request.getProjectId();
        if (!ObjectUtils.isEmpty(request.getIdNumber())){
            AssertUtil.assertTrue(StringUtil.isPhoneNumber(userPhone),"手机号输入错误");
        }
        Integer leaveOrNot = request.getLeaveOrNot();
        if (leaveOrNot==1){//入场
            if (!ObjectUtils.isEmpty(request.getIdNumber())){
                AssertUtil.assertTrue(StringUtil.isIdCard(request.getIdNumber()),"身份证号格式错误");
            }
            ManageTempUserRegistrationDO manageTempUserRegistrationDO = ManageTempUserRegistrationDtoMapper.INSTANCE.request2DO(request);
            List<ManageTempUserRegistrationDO> userRegistrationDOThis = manageTempUserRegistrationMapper.selectByPhoneAndName(userPhone,userName,projectId);
            AssertUtil.assertEmpty(userRegistrationDOThis,"当前手机用户已做进场登记，请先做离场登记");
            manageTempUserRegistrationDO.setEntranceTime(DateUtils.getNowDate());
            manageTempUserRegistrationDO.setCreateTime(DateUtils.getNowDate());
            manageTempUserRegistrationDO.setDeleted(0);
            manageTempUserRegistrationMapper.insertManageTempUserRegistration(manageTempUserRegistrationDO);
            return true;
        }else {//离场
            if (org.springframework.util.ObjectUtils.isEmpty(request.getApproachAddress())){
                return false;
            }
            List<ManageTempUserRegistrationDO> userRegistrationDO = manageTempUserRegistrationMapper.selectByPhoneAndName(userPhone,null,projectId);
            AssertUtil.assertTrue(!ObjectUtils.isEmpty(userRegistrationDO),"当前手机用户未做进场登记，请先做进场登记");
            ManageTempUserRegistrationDO aDo = userRegistrationDO.stream().filter(a -> userName.equals(a.getUserName()) && userPhone.equals(a.getUserPhone())).findFirst().orElse(null);
            AssertUtil.assertTrue(!ObjectUtils.isEmpty(aDo),"当前手机号和姓名与进场登记信息不一致，请检查输入。若进场登记错误，则请先做进场登记");
            ManageTempUserRegistrationDO manageTempUserRegistrationDO = ManageTempUserRegistrationDtoMapper.INSTANCE.request2DO(request);
            manageTempUserRegistrationDO.setUpdateTime(DateUtils.getNowDate());
            manageTempUserRegistrationDO.setId(aDo.getId());
            manageTempUserRegistrationMapper.updateManageTempUserRegistration(manageTempUserRegistrationDO);
            return true;
        }
    }

    /**
     *(云监管、云管理)临时人员进出场记录-填写手机号和姓名后查询
     * @param request
     * @return
     */
    @Override
    public Object verify(ManageTempUserRegistrationRequest request) {
        Long jiansheUnitId = SessionContext.getJiansheUnitId();
        String personInfo = request.getPersonInfo();
        AssertUtil.assertTrue(!org.springframework.util.ObjectUtils.isEmpty(personInfo),"手机号或身份证号不能为为空");
        if (!ObjectUtils.isEmpty(jiansheUnitId)&&!request.getSuperviseOrManage()){//云管理端查询
            List<Long> projectIds = jiansheProjectMapper.selectAllProjectId(jiansheUnitId);
            List<Map<String,Object>> userRegistrationVOThis = manageTempUserRegistrationMapper.selectByPersonInfo(personInfo,projectIds);
            if (!ObjectUtils.isEmpty(userRegistrationVOThis)) {
                Map<String, Object> map = userRegistrationVOThis.get(0);
                Object addressDetail = map.get("addressDetail");
                Object province = map.get("province");
                Object city = map.get("city");
                Object area = map.get("area");
                if (ObjectUtils.isEmpty(province)) {
                    province = "";
                }
                if (ObjectUtils.isEmpty(city)) {
                    city = "";
                }
                if (ObjectUtils.isEmpty(area)) {
                    area = "";
                }
                if (ObjectUtils.isEmpty(addressDetail)) {
                    addressDetail = "";
                }
                String address = province.toString() + city + area + addressDetail;
                map.put("addressDetail", address);
            }
            return userRegistrationVOThis;
        }else {//监管端查询
            List<Map<String,Object>> userRegistrationVOThis = manageTempUserRegistrationMapper.selectByPersonInfo(personInfo,new ArrayList<>());
            if (!ObjectUtils.isEmpty(userRegistrationVOThis)) {
                Map<String, Object> map = userRegistrationVOThis.get(0);
                Object addressDetail = map.get("addressDetail");
                Object province = map.get("province");
                Object city = map.get("city");
                Object area = map.get("area");
                if (ObjectUtils.isEmpty(province)) {
                    province = "";
                }
                if (ObjectUtils.isEmpty(city)) {
                    city = "";
                }
                if (ObjectUtils.isEmpty(area)) {
                    area = "";
                }
                if (ObjectUtils.isEmpty(addressDetail)) {
                    addressDetail = "";
                }
                String address = province.toString() + city + area + addressDetail;
                map.put("addressDetail", address);
            }
            return userRegistrationVOThis;
        }
    }


    /**
     * 临时人员进出场填写手机号和姓名后查询
     * @param request
     * @return
     */
    @Override
    public Object verifyAfterWrite(ManageTempUserRegistrationRequest request) {
        String userName = request.getUserName();
        String userPhone = request.getUserPhone();
        Long projectId = request.getProjectId();
        if (org.springframework.util.ObjectUtils.isEmpty(userName)|| org.springframework.util.ObjectUtils.isEmpty(userPhone)
                || org.springframework.util.ObjectUtils.isEmpty(projectId)){
            return "用户名、手机号或项目id为空";
        }
        //先从该项目中取入场登记记录，如果没有则跨平台全项目查询
        List<ManageTempUserRegistrationDO> userRegistrationDOs = manageTempUserRegistrationMapper.selectByPhone(userPhone,projectId);//从该项目查询
        if (!org.springframework.util.ObjectUtils.isEmpty(userRegistrationDOs)) {
            List<ManageTempUserRegistrationVO> registrationVOS = ManageTempUserRegistrationConvert.buildManageTempUserRegistrationVoList(userRegistrationDOs);
            ManageTempUserRegistrationVO userRegistrationVO = registrationVOS.stream().filter(vo -> userName.equals(vo.getUserName()) && userPhone.equals(vo.getUserPhone()))
                    .sorted(Comparator.comparing(ManageTempUserRegistrationVO::getEntranceTime).reversed())
                    .findFirst().orElse(new ManageTempUserRegistrationVO());
            if (!ObjectUtils.isEmpty(userRegistrationVO)){
                return userRegistrationVO;
            }else {
                return getManageTempUserRegistrationVO(userName, userPhone);
            }

        }else {
            return getManageTempUserRegistrationVO(userName, userPhone);
        }
    }

    @NotNull
    private ManageTempUserRegistrationVO getManageTempUserRegistrationVO(String userName, String userPhone) {
        List<ManageTempUserRegistrationDO> userRegistrationDOs = manageTempUserRegistrationMapper.selectByPhone(userPhone, null);//全平台全项目查询
        if (!org.springframework.util.ObjectUtils.isEmpty(userRegistrationDOs)) {
            List<ManageTempUserRegistrationVO> registrationVOS = ManageTempUserRegistrationConvert.buildManageTempUserRegistrationVoList(userRegistrationDOs);
            ManageTempUserRegistrationVO userRegistrationVO = registrationVOS.stream().filter(vo -> userName.equals(vo.getUserName()) && userPhone.equals(vo.getUserPhone()))
                    .max(Comparator.comparing(ManageTempUserRegistrationVO::getCreateTime)).orElse(new ManageTempUserRegistrationVO());
            userRegistrationVO.setReceiver(null);
            return userRegistrationVO;
        }
        return new ManageTempUserRegistrationVO();
    }

    @Override
    public Boolean updateByKey(ManageTempUserRegistrationRequest request) {
        ManageTempUserRegistrationDO manageTempUserRegistrationDO = ManageTempUserRegistrationDtoMapper.INSTANCE.request2DO(request);
        save(manageTempUserRegistrationDO);
        return true;
    }

    @Override
    public Boolean deleteByKey(long id) {
        manageTempUserRegistrationMapper.deleteById(id);
        return true;
    }


}
